package com.yootk.jdbc.config;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Aspect
public class TransactionActiveConfig {
    @Bean("txAdvice")
    public TransactionInterceptor transactionInterceptor(TransactionManager manager){
        RuleBasedTransactionAttribute readAttribute = new RuleBasedTransactionAttribute() ;
        readAttribute.setReadOnly(true);
        readAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        RuleBasedTransactionAttribute requireAttribute = new RuleBasedTransactionAttribute() ;
        requireAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        Map<String, TransactionAttribute> attributeMap = new HashMap<>() ;
        attributeMap.put("add*",requireAttribute) ;
        attributeMap.put("edit*",requireAttribute) ;
        attributeMap.put("delete*",requireAttribute) ;
        attributeMap.put("get*",readAttribute) ;
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource() ;
        source.setNameMap(attributeMap);
        TransactionInterceptor interceptor = new TransactionInterceptor(manager,source) ;
        return interceptor ;
    }
    @Bean
    public Advisor transcationActiveAdvisor(@Qualifier("txAdvice") TransactionInterceptor interceptor){
        String express = "execution(* com.yootk..service.*.*(..))" ;
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut() ;
        pointcut.setExpression(express);
        return new DefaultPointcutAdvisor(pointcut,interceptor) ;
    }
}
